﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Threading;

namespace SLServer
{
	class Program
	{
		private static byte[] m_DataBuffer = new byte[1024];
		//设置端口号
		private static int m_Port = 8099;
		private static int maxCount = 500;
		static Socket serverSocket;
		public static List<Socket> allClient = new List<Socket>();
		static void Main(String[] args)
		{
			//为了方便在本机上同时运行Client和Server，使用回环地址为服务的监听地址
			IPAddress ip = IPAddress.Parse("0.0.0.0");
			//IPAddress ip = IPAddress.Any;
			//实例化一个Socket对象，确定网络类型、Socket类型、协议类型
			serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			//Socket对象绑定IP和端口号
			serverSocket.Bind(new IPEndPoint(ip, m_Port));
			//挂起连接队列的最大长度为X，启动监听
			serverSocket.Listen(maxCount);

			Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
			//一个客户端连接服务器时创建一个新的线程
			Thread myThread = new Thread(ListenClientConnect);
			myThread.Start();
		}

		private static void SendMsgToAll(Object omsg)
		{
			string[] msg = omsg as string[];
			foreach (var m in msg)
			{
				Console.WriteLine("广播一条消息:{0}", m);
				//foreach (var item in allClient)
				for(int i = 0; i < allClient.Count; i ++)
				{
					Socket item = allClient[i];
					if (item != null && item.Connected)
					{
						try
						{
							string sendMessage = m;
							item.Send(Encoding.UTF8.GetBytes(sendMessage));
						}
						catch (Exception ex)
						{
							Console.WriteLine(ex.Message);
							if (item != null && item.Connected)
							{
								item.Shutdown(SocketShutdown.Both);
								item.Close();
							}
							if (allClient.Contains(item) != true)
							{
								allClient.Remove(item);
							}
						}
					}
				}
			}
		}

		//接收连接
		private static void ListenClientConnect()
		{
			while (true)
			{
				Console.WriteLine("INFO 等待用户加入数据");
				//运行到Accept()方法时会阻塞程序(同步Socket)。
				//收到客户端请求创建一个新的Socket Client对象继续执行
				Socket clientSocket = serverSocket.Accept();
				//clientSocket.Send(Encoding.UTF8.GetBytes("Server说:Client你好！"));
				//创建一个接受客户端发送消息的线程
				Thread reciveThread = new Thread(ReciveMessage);
				if (allClient.Contains(clientSocket) != true)
				{
					allClient.Add(clientSocket);
				}
				reciveThread.Start(clientSocket);

				GameLogic gl = new GameLogic();
				gl.EnterRoom(clientSocket);
			}
		}

		//发送消息
		private static void SendMessage(Object clientSocket)
		{

		}

		//接收消息
		private static void ReciveMessage(Object clientSocket)
		{
			if (clientSocket != null)
			{
				Socket m_ClientSocket = clientSocket as Socket;
				while (true)
				{
					if(m_ClientSocket == null)
					{
						Console.WriteLine("ERROR 连接不存在");
						return;
					}
					if (!m_ClientSocket.Connected)
					{
						Console.WriteLine("ERROR 未连接");
						return;
					}
					if(m_ClientSocket.Poll(10, SelectMode.SelectRead))
					{
						Console.WriteLine("ERROR 断开连接");
						return;
					}
					Console.WriteLine("INFO 等待接受数据");
					try
					{
						int reciverNumber = m_ClientSocket.Receive(m_DataBuffer);
						string msg = Encoding.UTF8.GetString(m_DataBuffer, 0, reciverNumber);
						Console.WriteLine("接收客户端:{0}消息:{1}", m_ClientSocket.RemoteEndPoint.ToString(), msg);

						GameLogic gl = new GameLogic();
						gl.CheckMsg(m_ClientSocket, msg);

						//Thread Brd = new Thread(SendMsgToAll);
						//Brd.Start(retMsg);
					}
					catch (Exception ex)
					{
						Console.WriteLine("ERROR " + ex.Message);
						m_ClientSocket.Shutdown(SocketShutdown.Both);
						m_ClientSocket.Close();
						if (allClient.Contains(m_ClientSocket) != true)
						{
							allClient.Remove(m_ClientSocket);
						}
						Console.WriteLine("ERROR 发送失败，自动断开");
						return;
					}
				}
			}
		}
	}
}
